package org.rqb.frame;

import org.rqb.entry.Message;
import org.rqb.panel.QueryLANDevicesPanel;
import org.rqb.socket.MySocket;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import static org.rqb.Constant.*;

public class ChatFrame extends JFrame {

    private final MySocket mySocket = MySocket.getInstance();
    private String sender; // 发送者ip
    private String receiver; // 接收者ip

    private JPanel chatPanel;
    private JTextArea inputFieldArea;

    private QueryLANDevicesPanel queryLANDevicesPanel;



    public ChatFrame(String sender, String receiver) throws HeadlessException {
        super("和" + receiver + "聊天");
        this.sender = sender;
        this.receiver = receiver;
        this.queryLANDevicesPanel = queryLANDevicesPanel;
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        this.setSize(new Dimension(CHAT_FRAME_WIDTH, CHAT_FRAME_HEIGHT));
        this.setLocationRelativeTo(null);

        chatPanel = new JPanel();
        chatPanel.setLayout(new BoxLayout(chatPanel, BoxLayout.Y_AXIS));
        JScrollPane scrollPane = new JScrollPane(chatPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); // 禁止显示水平滚动条
        scrollPane.setPreferredSize(new Dimension(MAX_CHAT_WIDTH, MAX_CHAT_HEIGHT)); // 限制聊天区域的高度
        scrollPane.setMaximumSize(new Dimension(MAX_CHAT_WIDTH, MAX_CHAT_HEIGHT)); // 设定最大高度

        inputFieldArea = new JTextArea(3, 20); // 设定初始行数和列数
        inputFieldArea.setLineWrap(true); // 启用换行
        inputFieldArea.setWrapStyleWord(true); // 按单词换行
        JButton sendButton = new JButton("发送");
        sendButton.addActionListener(new SendMessageAction());
        // 添加 KeyListener 来处理 Enter 键
        inputFieldArea.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (e.isShiftDown()) {
                        // Shift + Enter: 在文本框中换行
                        inputFieldArea.append("\n");
                    } else {
                        // 其他 Enter: 发送消息
                        e.consume(); // 消费事件，防止添加新行
                        String message = inputFieldArea.getText().trim(); // 去除前后空白
                        if (!message.isEmpty()) {
                            sendMessage(new Message(sender, receiver, message, Message.MessageType.TEXT));
                            inputFieldArea.setText(""); // 发送后清空输入框
                        }
                    }
                }
            }
        });

        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.add(inputFieldArea, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);

        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
        this.add(inputPanel, BorderLayout.SOUTH);
    }

    private class SendMessageAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String message = inputFieldArea.getText();
            if (!message.isEmpty()) {
                sendMessage(new Message(sender, receiver, message, Message.MessageType.TEXT));
                inputFieldArea.setText("");
            }
        }
    }

    private void sendMessage(Message message) {
        // 发送消息，并根据返回值判断是否成功
        if (mySocket.sendMessage(message, PORT)) { // 发送成功
            appendMessage(message.getContent(), SwingConstants.RIGHT, new Color(173, 216, 230)); // 浅蓝色背景
        } else { // 发送失败
            appendMessage(message.getContent(), SwingConstants.RIGHT, Color.RED); // 红色背景
        }
    }


    public void receiveMessage(Message message) {
        appendMessage(message.getContent(), SwingConstants.LEFT,new Color(144, 238, 144));
    }


    private void appendMessage(String message, int alignment,Color background) {
        // 创建一个新的面板，用于存放消息标签
        JPanel messagePanel = new JPanel();
        messagePanel.setLayout(new BoxLayout(messagePanel, BoxLayout.X_AXIS)); // 横向布局

        JLabel messageLabel = new JLabel(message);
        messageLabel.setOpaque(true);
        messageLabel.setFont(new Font("Serif", Font.PLAIN, FONT_SIZE));
        messageLabel.setBorder(BorderFactory.createEmptyBorder(5, 8, 5, 8)); // 较小的边距
        messageLabel.setBackground(background);
        // 设置不同的背景色和对齐方式
        if (alignment == SwingConstants.RIGHT) {
            // 浅蓝色
            messagePanel.add(Box.createHorizontalGlue()); // 向左添加弹性空白区域
            messagePanel.add(messageLabel); // 添加消息标签
        } else {
            messagePanel.add(messageLabel); // 添加消息标签
            messagePanel.add(Box.createHorizontalGlue()); // 向右添加弹性空白区域
        }

        chatPanel.add(messagePanel); // 将消息面板添加到聊天面板中

        // 重新验证和更新显示
        chatPanel.revalidate();
        chatPanel.repaint();

        // 自动滚动到最新消息
        SwingUtilities.invokeLater(() -> {
            JScrollBar vertical = ((JScrollPane) chatPanel.getParent().getParent()).getVerticalScrollBar();
            vertical.setValue(vertical.getMaximum()); // 自动滚动到底部
        });
    }


}
